#!/usr/bin/env python3
# -*- coding: utf-8 -*-

' a win tool to azw3 files path and convert azw3 files to mobi files. '

__author__ = 'kevin deng'


import os
import sys
import getopt
import traceback
from shutil import copyfile
import lib.kindleunpack as kindleunpack


_ifile_type = ".azw3"
_ofile_type = ".mobi"


def unpack_azw3(input_file, output_dir, apnxfile, epubversion, use_hd, dump, writeraw, splitcombos):
    try:
        kindleunpack.unpackBook(input_file, output_dir, apnxfile, epubversion, use_hd, dodump=dump, dowriteraw=writeraw, dosplitcombos=splitcombos)
        return 0
    except Exception as e:
        print("Error: %s" % e)
        print(traceback.format_exc())
        return -1

def azw3_to_mobis(dir, tmpdir, epubversion, use_hd, dump, writeraw, splitcombos):  
    apnxfile = None
    yid = os.walk(dir)  
    for rootDir, pathList, fileList in yid:  
        for file in fileList:  
            filepath = os.path.join(rootDir, file)

            # 校验文件后缀名
            fext = os.path.splitext(file)
            if fext[1].lower() == _ifile_type:

                # 创建输出目录
                name = os.path.split(file)[1]
                ofpath = tmpdir + "\\" + os.path.splitext(name)[0];
                if os.path.exists(ofpath) == False:
                    print(ofpath)
                    os.makedirs(ofpath)

                # unpack azw3
                if unpack_azw3(filepath, ofpath, apnxfile, epubversion, use_hd, dump, writeraw, splitcombos) == 0:

                    # find and convert opf to mobi
                    opfname = ofpath + "\\mobi8\\OEBPS\\content.opf"
                    cmd = os.getcwd() + "\\kindlegen_win32_v2_9\\kindlegen.exe -dont_append_source \"" + opfname + "\""
                    print(cmd)
                    os.system(cmd)

                    # move mobi to origin path
                    mfname = ofpath + "\\mobi8\\OEBPS\\content.mobi"
                    moname = os.path.splitext(filepath)[0] + ".mobi"
                    copyfile(mfname, moname)

def azw3_to_mobis_easy(dir, tmpdir):
    epubversion = '2'
    use_hd = False
    dump = False
    writeraw = True
    splitcombos = True    
    azw3_to_mobis(dir, tmpdir, epubversion, use_hd, dump, writeraw, splitcombos)


def azw3_to_mobis_Main():
    args = sys.argv
    print(args)

    if len(args)<5:
        print(args[0], '-i input_dir -o temp_dir')
        return -1

    #getopt函数的第二个参数是短参数选项。"h"是一个开关选项；"i:"和"o:"则表示后面应该带一个参数。
    #getopt函数的第三个参数[, long_options]为可选的长选项参数.
    #getopt函数返回两个列表：opts和args。opts为分析出的格式信息。args为不属于格式信息的剩余的命令行参数。
    #   opts是一个两元组的列表。每个元素为：(选项串,附加参数)。如果没有附加参数则为空串''。
    #opts, args = getopt.getopt(sys.argv[1:], "hi:o:")
    opts, args = getopt.getopt(sys.argv[1:], "hi:o:", ["version", "file="])
    input_dir=""
    temp_dir=""
    # print("opts:", opts)

    for op, value in opts:
        if op == "-i":
            input_dir = value
        elif op == "-o":
            temp_dir = value
        elif op == "-h":
            print("args[0], '-i input_dir -o temp_dir'")
            sys.exit()

    azw3_to_mobis_easy(input_dir, temp_dir)

# 生成mobi文件。
if __name__=='__main__':
    azw3_to_mobis_Main()


